<?php

declare(strict_types=1);

namespace app\common\model;

use think\facade\Event;
use think\facade\Db;

class Examine extends Base
{

    protected $name = 'examine';
    public function getCateTextAttr($value, $data)
    {
        return Cate::where('id', $data['cate'])->value('title') ?? "";
    }

    public function getTypesTextAttr($value, $data)
    {
        return self::getTypeList($data['types'], 1);
    }
    public static function getTypeList($value, $type = 1)
    {
        $list = ['1' => '初考', '2' => '补考'];
        return $type == 1 ? $list[$value] : $list;
    }

    public function getStatusTextAttr($value, $data)
    {
        return self::getStatusList($data['status'], 1);
    }
    public function getStatusList($value, $type = 1)
    {
        $list = [1 => '未开始', 2 => '考试中', 3 => '已结束'];
        return $type == 1 ? $list[$value] : $list;
    }
    public function getTimeTextAttr($value, $data)
    {
        return round($data['duration'] / 60) . '分钟';
    }
    public static function _save($param, $logs)
    {
        parent::startTrans();
        try {
            $exam_time = explode(' - ', $param['exam_time']);
            $param['duration'] = strtotime($exam_time[1]) - strtotime($exam_time[0]);
            $param['start_time'] = strtotime($param['exam_date'] . $exam_time[0]);
            $param['end_time'] = strtotime($param['exam_date'] . $exam_time[1]);
            $param['score'] = 100;
            $count = parent::where(['cate' => $param['cate'], 'types' => 1])->count();
           
            if (isset($param['id']) && $param['id']) {
                $original = self::where($logs['pk'], $param[$logs['pk']])->find();
                if (empty($original)) {
                    return ['code' => -1, 'msg' => '记录不存在，请检查！'];
                }
                $password = !empty($param['password']) ? $param['password'] : '';
                if (empty($password)) {
                    $param['password'] = $original['password'];
                } else {
                    $param['password'] = md5($password);
                }
                $logs['original'] = $original;
                $model = self::update($param);
                $logs['operation'] = 'save';
                if ($logs['writeLog']) {
                    $logs['model'] = $model;
                    Event::trigger('Logs', $logs);
                }
            } else {
                $paper_id = Paper::where('cate', $param['cate'])
                    ->field('DISTINCT id') // 如果需要获取特定字段，使用DISTINCT
                    ->limit(1)
                    ->orderRaw('rand()')->value('id');
                if (empty($paper_id)) {
                    return ['code' => -1, 'msg' => '暂无考题试卷！'];
                }
                $password = !empty($param['password']) ? $param['password'] : '111111';
                $param['password'] = md5($password);
                $param['paper_id'] = $paper_id;
                $model = parent::create($param);
            }
            if (!empty($param['uid'])) {
                ExamineUser::addUser($model, $param['uid']);
            }
            parent::commit();
            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    public static function getTakeOverTableList($that, $param, $filed = '*', $count = 0)
    {
        try {
            $time = time();
            foreach ($that as $key => $v) {
                if ($v->end_time < $time) {
                    $v->status = 3;
                } else if ($v->start_time > $time) {
                    $v->status = 1;
                } else {
                    $v->status = 2;
                }
                $v->save();
            }
            return ['code' => 0, 'data' => $that, 'count' => $count];
        } catch (\Exception $e) {
            return [];
        }
    }
    
    /**
     * 获取当前题目
     */
    public static function getTopic($id){
        try {
            $info = Exam::where(['id'=>$id])->find();
            $list = Db::query("SHOW FULL COLUMNS FROM exam");
            $data = [];
            foreach($list as $k=>$value){
                if(in_array($value['Field'],['A','B','C','D','E'])){
                    if(!empty($info[$value['Field']])){
                        $data[]=[
                            'key'=> $value['Field'],
                            'value'=> $value['Field'].'.'.$info[$value['Field']],
                        ];
                    }
                }
            }
            $list = [
                'id'=>$info['id'],
                'title'=>$info['title'],
                'images'=>$info['images'],
                'list'=>$data,
            ];
            return $list;
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
